import 'package:getx_demo/common/apis/apis.dart';
import 'package:getx_demo/common/entities/entities.dart';
import 'package:getx_demo/common/routers/routes.dart';
import 'package:getx_demo/common/store/store.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'index.dart';

class LoginController extends GetxController {
  LoginController();

  final state = LoginState();

  final nameTextController = TextEditingController();
  final pwdTextController = TextEditingController();

  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.name = UserStore.to.username;
    state.pwd = UserStore.to.pwd;
    nameTextController.text = state.name;
    pwdTextController.text = state.pwd;
  }

  void switchPwdVisible() {
    state.pwdIsVisible = !state.pwdIsVisible;
    update();
  }

  void login() async {
    var response = await UserRequest.login(
      username: nameTextController.text,
      password: pwdTextController.text,
    );
    if (response != null) {
      UserStore.to.setUsername(nameTextController.text);
      UserStore.to.setPwd(pwdTextController.text);
      final token = (response.result['token'] ?? '') as String;
      await UserStore.to.setToken(token);
      final info = response.result['user']['user'];
      _saveUserInfo(info);
      Get.offAndToNamed(RouteNames.mainTab);
    }
  }

  void getUserInfo() async {
    var response = await UserRequest.getUserInfo();
    if (response != null) {
      final info = response.result['user'];
      _saveUserInfo(info);
    }
  }

  void _saveUserInfo(Map<String, dynamic> json) {
    final user = ErdsUserLoginInfo.fromJson(json);
    UserStore.to.saveUserInfo(user);
  }

  void forgetPwd() {
    Get.toNamed(RouteNames.forgetPwd);
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
